package com.ray.depot.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.flyong.cache.query.cache.CacheConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.ray.auth.system.emun.UseStatus;
import com.ray.depot.service.LibraryService;
import com.ray.depot.service.WarehouseService;
import com.ray.depot.table.entity.Warehouse;
import com.ray.depot.table.entity.WarehouseExample;
import com.ray.depot.table.entity.WarehouseExample.Criteria;
import com.ray.depot.table.mapper.WarehouseMapper;
import com.xiaoleilu.hutool.util.StrUtil;
import com.zjhc.flyhong.common.datastructure.TreeNode;
import com.zjhc.flyhong.common.function.enums.DeleteEnum;
import com.zjhc.flyhong.common.function.exception.BussinessException;
import com.zjhc.flyhong.common.function.operator.LoginUser;
import com.zjhc.flyhong.common.function.operator.PageDto;
import com.zjhc.flyhong.common.util.UUIDUtil;
import com.zjhc.flyhong.common.web.ErrorMsg;
import com.zjhc.flyhong.common.web.Result;
import com.zjhc.flyhong.common.web.SuccessMsg;
import com.zjhc.flyhong.common.web.base.BaseService;

@Service
public class WarehouseServiceImpl extends BaseService implements WarehouseService {
	/** 日志对象 **/
	private static Logger logger = Logger.getLogger(WarehouseServiceImpl.class);

	@Autowired
	private WarehouseMapper warehouseMapper;
	@Autowired
	private LibraryService libraryService;

	@Transactional
	@CacheConfig(paramsSize=1,add=true,id="warchouseId", clearKey="warehouseList")
	public Result<Object> addWarehouse(Warehouse params, LoginUser user) {
		Result<Object> result = null;
		result = new Result<Object>(0, SuccessMsg.OP_SUCCESS);
		// 校验数据
		if (existWarehouse(params, user, false)) {
			return new Result<Object>(-1, "已经存在改类型的仓库");
		}

		params.setTenantId(user.getTenantId());
		params.setWarchouseId(UUIDUtil.getUUID());
		params.setIsDelete(DeleteEnum.USE.getValue());
		this.setUserForAdd(params, user);
		int count = warehouseMapper.insertSelective(params);
		if (count != 1) {
			logger.error("WarehouseServiceImpl=>addWarehouse is error");
			throw new BussinessException(-1, ErrorMsg.INSERT_ERROR);
		}
		return result;
	}


	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	@CacheConfig(key="warchouse",paramsSize=1,query=true,expire=1800)
	public Warehouse queryWarehouse(String id, LoginUser user) {
		return warehouseMapper.selectByPrimaryKey(id);
	}

	@Transactional
	@CacheConfig(key="warchouse",paramsSize=1,update=true,id="warchouseId", clearKey="warehouseList")
	public Result<Object> updateWarehouse(Warehouse params, LoginUser user) {
		Result<Object> result = null;
		result = new Result<Object>(0, SuccessMsg.OP_SUCCESS);
		// 校验数据
		if (existWarehouse(params, user, true)) {
			return new Result<Object>(-1, "已经存在改类型的仓库");
		}
		this.setUserForUpdate(params, user);
		int count = warehouseMapper.updateByPrimaryKeySelective(params);
		if (count != 1) {
			logger.error("WarehouseServiceImpl=>editWarehouse is error");
			throw new BussinessException(-1, ErrorMsg.INSERT_ERROR);
		}
		return result;
	}

	@Transactional
	@CacheConfig(key="warehouse",paramsSize=1,delete=true, clearKey="warehouseList")
	public Result<Object> deleteWarehouse(String id, LoginUser user) {
		Result<Object> result = null;
		result = new Result<Object>(0, SuccessMsg.OP_SUCCESS);
		Warehouse params = new Warehouse();
		params.setWarchouseId(id);
		params.setIsDelete(DeleteEnum.DELETE.getValue());
		this.setUserForUpdate(params, user);
		int count = warehouseMapper.updateByPrimaryKeySelective(params);
		if (count != 1) {
			logger.error("WarehouseServiceImpl=>deleteWarehouse is error");
			throw new BussinessException(-1, ErrorMsg.INSERT_ERROR);
		}
		//删除仓库对应的库位
		libraryService.deleteLibraryByWarehouseId(id, user);
		return result;
	}

	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	@CacheConfig(key="warehouseList",query=true,paramsSize=2,expire=1800)
	public PageDto<Warehouse> queryWarehouse(Warehouse params, PageDto<Warehouse> page, LoginUser user) {
		WarehouseExample example = new WarehouseExample();
		Criteria criteria = example.createCriteria();
		// 超级管理员能查看全部
		if (!user.isSuperManager()) {
			criteria.andTenantIdEqualTo(user.getTenantId());
		}
		criteria.andIsDeleteEqualTo(DeleteEnum.USE.getValue());
		this.setExamplePage(example, page);
		page.setTotal(warehouseMapper.countByExample(example));
		page.setRecords(warehouseMapper.selectByExample(example));
		return page;
	}
	
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	private boolean existWarehouse(Warehouse params, LoginUser user, boolean isUpdate) {
		WarehouseExample example = new WarehouseExample();
		Criteria criteria = example.createCriteria();
		criteria.andTenantIdEqualTo(user.getTenantId());
		criteria.andIsDeleteEqualTo(DeleteEnum.USE.getValue());
		criteria.andWarchouseTypeEqualTo(params.getWarchouseType());
		if(isUpdate){
			criteria.andWarchouseIdNotEqualTo(params.getWarchouseId());
		}
		long count = warehouseMapper.countByExample(example);
		return count != 0;
	}


	@Override
	@CacheConfig(key="warehouseList",query=true,paramsSize=1,expire=1800)
	public List<TreeNode> queryWarehouseList(String id, LoginUser user) {
		if(StrUtil.isNotBlank(id)){
			return new ArrayList<TreeNode>();
		}
		List<TreeNode> list = new ArrayList<TreeNode>();
		WarehouseExample example = new WarehouseExample();
		Criteria criteria = example.createCriteria();
		// 超级管理员能查看全部
		if (!user.isSuperManager()) {
			criteria.andTenantIdEqualTo(user.getTenantId());
		}
		criteria.andIsDeleteEqualTo(DeleteEnum.USE.getValue());
		
		TreeNode node = null;
		for(Warehouse Warehouse : warehouseMapper.selectByExample(example)){
			node = new TreeNode(Warehouse.getWarchouseId(), Warehouse.getWarchouseName(),0, true);
			node.setValue(Warehouse);
			list.add(node);
		}
		return list;
	}


	@Override
	@CacheConfig(key="warehouseList",query=true,paramsSize=1,expire=1800)
	public List<Warehouse> queryWarehouse(Warehouse warehouse, LoginUser user) {
		WarehouseExample example = new WarehouseExample();
		Criteria criteria = example.createCriteria();
		criteria.andTenantIdEqualTo(user.getTenantId());
		criteria.andWarchouseStatusEqualTo(UseStatus.ON.getType());
		criteria.andIsDeleteEqualTo(DeleteEnum.USE.getValue());
		return warehouseMapper.selectByExample(example);
	}
}
